<script setup>
//定义用户列表对象，初始值是空
import {inject, onMounted, ref} from "vue";
import {doDelete, doGet} from "../http/httpRequest.js";
import {clearToken, confirmMessage, showMessage} from "../util/utils.js";
import {useRoute, useRouter} from "vue-router";

//定义router对象，该对象中提供了一些路由方法供我们使用，比如router.push(), router.go()
let router = useRouter();
//定义route对象，该对象提供了一些路由属性/字段供我们使用，比如route.path;  route.params; 等等
let route = useRoute();

//定义用户列表对象，初始值是空
let userList = ref([{}])

//页面元素渲染后就会执行该函数钩子
onMounted(() => {
  //查询用户列表数据（分页）
  loadUserByPage(1);
})

//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

const loadUserByPage = (current) => {
  doGet('/api/users', {
    current : current //前面的current是参数名，后面的current是参数值
  }).then(resp => {
    if (resp.data.code === 200) {
      userList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (value) => {
  loadUserByPage(value);
}

//查看详情
const view = (id) => {
  // /dashboard/user/7   /dashboard/user/11
  router.push('/dashboard/user/' + id);
}

//添加用户
const add = () => {
  router.push('/dashboard/user/add');
}

//编辑函数
const edit = (id) => {
  router.push('/dashboard/user/edit/' + id);
}

//子页面注入父页面提供的reload函数
let flushPage = inject('flush');
let data = inject('myData');

//删除用户
const del = (id) => {
  console.log(data);
  //删除前，让用户确认一下
  confirmMessage('您确定要删除此数据吗？').then(() => { //点确定就触发then函数
    doDelete('/api/user/' + id, {}).then(resp => {
      if (resp.data.code === 200) {
        showMessage('删除成功', 'success')
        //页面要刷新一下，用传统方式把页面刷新一下
        //window.location.reload();
        //局部刷新
        flushPage();
      } else {
        showMessage('删除失败，原因：' + resp.data.msg, 'error')
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消删除', 'warning')
  })
}

//定义一个用户数组，初始值是空
let userIdArr = [];

//勾选或取消checkbox时会执行该函数
const handleSelectionChange = (newSelection) => {
  userIdArr = [];
  newSelection.forEach(item => {
    let id = item.id;
    userIdArr.push(id);
  })
}

//批量删除用户
const batchDel = () => {
  //判断用户有没有选择数据，没有选数据，提示他选择要删除的数据
  if (userIdArr.length <= 0) {
    showMessage('请选择要删除的数据', 'warning');
    return;
  }
  confirmMessage('您确定要删除这些数据吗？').then(() => { //点确定就触发then函数
    //发送请求，批量删除
    let ids = userIdArr.join(','); // 数组[1,3,5,6,8,12]  ==> ids = "1,3,5,6,8,12";
    doDelete('/api/user', {
      ids : ids
    }).then(resp => {
      if (resp.data.code === 200) {
        showMessage('批量删除成功', 'success');
        //刷新一下页面(js原始方式)
        //window.location.reload();
        //局部刷新
        flushPage();
      } else {
        showMessage('批量删除失败，原因：' + resp.data.msg, 'error');
      }
    })
  }).catch(() => { //点取消就触发catch函数
    showMessage('取消批量删除', 'warning')
  })
}
</script>

<template>
  <el-button type="primary" @click="add">添加用户</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>

  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="65"/>
    <el-table-column property="loginAct" label="账号"/>
    <el-table-column property="name" label="姓名"/>
    <el-table-column property="phone" label="手机"/>
    <el-table-column property="email" label="邮箱"/>
    <el-table-column property="createTime" label="创建时间"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination :background="true"
                 layout="prev, pager, next, jumper, ->, total"
                 :total="total"
                 :page-size="pageSize"
                 @current-change="toPage"/>
</template>

<style scoped>
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>